package data.vectors.implementation;

import java.util.HashSet;

import data.vectors.DoubleVector;
import data.vectors.DoubleVectorIterator;
import data.vectors.DoubleVectorWritable;


/**
 * Builds a full double vector in memory
 * @author denoyer
 *
 */


public class DoubleVector_Full_Memory extends DoubleVectorWritable {

	/**
	 * The values of the vector
	 */
	private double[] values;
	
        private HashSet<Integer> non_null;
       
        
        
	/**
	 * The size of the vector
	 */
	private int size;
	
	public DoubleVector_Full_Memory(int size)
	{
		values=new double[size];
		this.size=size;
                non_null=new HashSet<Integer>();
	}

	/**
	 * Create a new memory vector from a vector
	 * @param v
	 */
	public DoubleVector_Full_Memory(DoubleVector v)
	{
		this.size=v.size();
                non_null=new HashSet<Integer>();
		values=new double[size];
		DoubleVectorIterator it=v.getIterator();
		while(it.hasNext())
		{
			it.next();
                        setValue(it.getCurrentFeature(),it.getCurrentValue());
		}
	}
	
	public final double getValue(int i) {
		return(values[i]);
	}

	public final int size() {
		return size;
	}

	public void setValue(int feature, double value) {
                if (value==0) non_null.remove(feature);
                else
                    non_null.add(feature);
                
		this.values[feature]=value;
	}

	public int getNumberNonNullValues() {
		return non_null.size();
	}

	
	public DoubleVectorIterator getIterator() {
		return(new BasicDoubleVectorIterator(this));
	}

	
	public DoubleVectorIterator getNonNullIterator() {
		return(new IT());
	}

        private class IT implements DoubleVectorIterator
        {
            private int[] list;
            private int pos=-1;
            
            public IT()
            {
            	list=new int[non_null.size()];
            	int p=0;
            	for(Integer i:non_null)
            		list[p++]=i;
                pos=-1;
            }
                    
        public final boolean hasNext() 
        {
            return(pos<list.length-1);
        }

        public final int getCurrentFeature() {
        return(list[pos]);
        }

        public final double getCurrentValue() {
            return(getValue(getCurrentFeature()));
        }

        public void next() {
            pos++;
        }
            
        }
        
}
